package com.irdstudio.efp.flow.api.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.ApplicationConstance;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.vo.EngineHttpRequestVO;
import com.irdstudio.basic.framework.web.util.HttpClientUtil;
import com.irdstudio.basic.sequence.service.facade.SequenceService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.flow.common.constance.FlowConstance;
import com.irdstudio.efp.flow.executor.util.AbstractController;
import com.irdstudio.efp.flow.service.FlowCommonService;
import com.irdstudio.efp.flow.service.facade.BizFlowInfoService;
import com.irdstudio.efp.flow.service.facade.FlowUrlConfigService;
import com.irdstudio.efp.flow.service.vo.BizFlowInfoVO;
import com.irdstudio.efp.riskm.common.RiskColltConstant;
import com.irdstudio.efp.riskm.common.RiskwarningConstant;
import com.irdstudio.efp.riskm.service.facade.PspCheckTaskAppService;
import com.irdstudio.efp.riskm.service.facade.PspSpecCheckCusService;
import com.irdstudio.efp.riskm.service.vo.PspCheckTaskAppVO;
import com.irdstudio.efp.riskm.service.vo.PspSpecCheckCusVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * *
 *
 * @author
 * @version 0.1
 * @date 2019/9/15
 * @since 2019/9/15
 */

@RestController
@RequestMapping("/api")
public class PspCheckTaskAppController extends AbstractController {

    @Autowired
    @Qualifier("pspCheckTaskAppService")
    private PspCheckTaskAppService pspCheckTaskAppService;
    @Autowired
    @Qualifier("bizFlowInfoService")
    private BizFlowInfoService bizFlowInfoService;
    @Autowired
    @Qualifier("flowUrlConfigService")
    private FlowUrlConfigService flowUrlConfigService;
    @Autowired
    @Qualifier("dbSeqService")
    private SequenceService sequenceService;
    @Autowired
    @Qualifier("pspSpecCheckCusService")
    private PspSpecCheckCusService pspSpecCheckCusService;
    @Autowired
    private FlowCommonService flowCommonService;

    /**
     * 功能描述：提交数据
     * @param inPspCheckTaskAppVO
     * @return
     */
    @RequestMapping(value = "/psp/check/task/app/submit", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<Integer> submit(@RequestBody PspCheckTaskAppVO inPspCheckTaskAppVO) {
        int outputVo=0;
        setUserInfoToVO(inPspCheckTaskAppVO);
        List<PspCheckTaskAppVO> qs = new ArrayList<PspCheckTaskAppVO>();
        qs = pspCheckTaskAppService.queryByConditions(inPspCheckTaskAppVO.getChkTaskNo(), inPspCheckTaskAppVO.getCusId(), inPspCheckTaskAppVO.getCertCode());
        if(qs != null){
            for(PspCheckTaskAppVO item: qs){
                if (item.getApproveStatus() != null){
                    if(item.getApproveStatus().equals(ConsoleConstant.APRV_STATUS_01)|| item.getApproveStatus().equals(ConsoleConstant.APRV_STATUS_02) || item.getApproveStatus().equals(ConsoleConstant.APRV_STATUS_05)){
                        outputVo = -1;
                        return setResponseMessage(outputVo, "发起检查登记审批流程失败!原因: 该数据未处理" );
                    }
                }
            }
        }
        setUserInfoToVO(inPspCheckTaskAppVO);
        inPspCheckTaskAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
        inPspCheckTaskAppVO.setChkState(RiskwarningConstant.STD_ZX_CHK_STATE_00);
        inPspCheckTaskAppVO.setCreateTime(TimeUtil.getCurrentDateTime());
        inPspCheckTaskAppVO.setCreateUser(inPspCheckTaskAppVO.getLoginUserId());
        inPspCheckTaskAppVO.setLastUpdateUser(inPspCheckTaskAppVO.getLoginUserId());
        inPspCheckTaskAppVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        String pSeq = inPspCheckTaskAppVO.getBizSerno();
        try {
            if (Objects.isNull(pSeq) || pSeq.length()==0){
                pSeq = sequenceService.getSequence("PSP_CHKCUS_BIZ_SERNO","null","null");
            }
        } catch (Exception e) {
            logger.error("获取序列号失败！");
            e.printStackTrace();
        }
        inPspCheckTaskAppVO.setBizSerno(pSeq);


//        发起流程
        logger.info("即将发起检查登记审批流程，信息为:" + JSON.toJSONString(inPspCheckTaskAppVO));
        // 事件ID
        String eventId = "mPspCheckTaskAppEnter";
        // 获取流程ID
        String flowId = "FW20191015000000000";
//        inPspCheckTaskAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
        BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
        bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_08);
        bizFlowInfoVO.setBizFlowId(flowId);
        List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);

        // 获取流程ID
        logger.info("查询到的业务流程参数为："+ JSONObject.toJSONString(listFlow));
        if (Objects.nonNull(listFlow) && listFlow.size()>0) {
            bizFlowInfoVO = listFlow.get(0);
            flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
        } else {
            //提交失败 待发起
//            inPspCheckTaskAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
//            pspCheckTaskAppService.updateByPk(inPspCheckTaskAppVO);
            outputVo = -1;
            return setResponseMessage(outputVo, "未配置相关信息提交失败!");
        }
        EngineHttpRequestVO eVo = new EngineHttpRequestVO();
        // 业务法人机构
        eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
        // 业务流水号
        eVo.setE_bizSerno(inPspCheckTaskAppVO.getBizSerno());
        eVo.setFlowId(flowId);
        //事件ID
        eVo.setEventId(eventId);
        eVo.setData(inPspCheckTaskAppVO);
        eVo.setG_bizSerno(inPspCheckTaskAppVO.getBizSerno());
        if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
            outputVo = -1;
            return setResponseMessage(outputVo, "发起审批流程失败!原因: 流程岗位已失效");
        }
        try {
            HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
            //更新 申请日期
//            outputVo = pspCheckTaskAppService.updateByPk(inPspCheckTaskAppVO);
            pspCheckTaskAppService.insertPspCheckTaskApp(inPspCheckTaskAppVO);
            updateCus(inPspCheckTaskAppVO);
            //更新 检查登记状态
            PspSpecCheckCusVO pspSpecCheckCusVO = new PspSpecCheckCusVO();
            pspSpecCheckCusVO.setBizSerno(inPspCheckTaskAppVO.getChkTaskNo());
            pspSpecCheckCusVO.setCusId(inPspCheckTaskAppVO.getCusId());
            pspSpecCheckCusVO.setChkInputSts(RiskwarningConstant.STD_ZX_CHK_STATE_02);
            outputVo = pspSpecCheckCusService.updateCusIdByPk(pspSpecCheckCusVO);
        } catch (Exception e) {
            // 发起失败
            e.printStackTrace();
            logger.error("PspSpecCheckCusVO", e.getMessage());
            outputVo = -1;
            return setResponseMessage(outputVo, "发起检查登记审批流程失败!原因: " + e.getMessage());
        }
        return getResponseData(outputVo);
    }

    private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
        ResponseData<Integer> responseData = new ResponseData<Integer>();
        responseData.setMessage(message);
        responseData.setCode(ApplicationConstance.FAILURE);
        responseData.setSuccess(true);
        return responseData;
    }

    /**
     * 根据检查任务编号和客户id更新检查客户表
     * @author xiezw
     * @params  * @param null
     * @return
     * @date 2019/10/24 14:41
     * @version 0.1
     */
    private void updateCus(PspCheckTaskAppVO inPspCheckTaskAppVO){
        PspSpecCheckCusVO pspSpecCheckCusVO = new PspSpecCheckCusVO();
        pspSpecCheckCusVO.setBizSerno(inPspCheckTaskAppVO.getChkTaskNo());
        pspSpecCheckCusVO.setCusId(inPspCheckTaskAppVO.getCusId());
        PspSpecCheckCusVO qs = pspSpecCheckCusService.queryByCusIdBizSerno(pspSpecCheckCusVO);
        qs.setTaskHdlUser(inPspCheckTaskAppVO.getLoginUserId());
        qs.setTaskHdlTime(TimeUtil.getCurrentDateTime());
        qs.setLastUpdateUser(inPspCheckTaskAppVO.getLoginUserId());
        qs.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        pspSpecCheckCusService.updateCusIdByPk(qs);
    }

    @RequestMapping(value="/psp/check/task/apps", method=RequestMethod.POST)
    public @ResponseBody ResponseData<PspCheckTaskAppVO> queryByTask(@RequestBody PspSpecCheckCusVO inVo) {
        PspCheckTaskAppVO outputVo = null;
        List<PspCheckTaskAppVO> querys = pspCheckTaskAppService.queryByConditions(inVo.getBizSerno(),inVo.getCusId(),inVo.getCertCode());
        if (Objects.isNull(querys) || querys.isEmpty() || querys.size()>1){
            return ResponseData.create(outputVo,ApplicationConstance.FAILURE,"通过条件查询失败",false);
        }
        outputVo = querys.get(0);
        return ResponseData.create(outputVo,ApplicationConstance.SUCCESS,"通过条件查询成功！",true);
    }
}
